package git.common;

import java.io.*;

import org.apache.log4j.Logger;

public final class ProcessUtils
{
    private static Logger jrn = Logger.getLogger("layala.journal");
    
    public static void unpackage(String pkgName, File workDir)
 		throws Exception
 	{
		ProcessUtils.sysCommand("7z x \"" + pkgName + "\" -y", workDir);
    }
    
    public static int sysCommand(String cmd, File workDir)
		throws Exception
	{
        jrn.info(cmd);
        Process p = Runtime.getRuntime().exec(cmd, null, workDir);

        Thread t1 = new InputStreamTracer(p.getInputStream(), jrn);
        Thread t2 = new InputStreamTracer(p.getErrorStream(), jrn);
        t1.start();
        t2.start();
        //t1.join();
        //t2.join();
        
        return p.waitFor();
	}
    public static int sysCommand(String[] cmdArray, File workDir)
    	throws IOException, InterruptedException
	{
    	for (int i = 0; i < cmdArray.length; ++i)
    		jrn.info(cmdArray[i]);
    	
	    Process p = Runtime.getRuntime().exec(cmdArray, null, workDir);
	    jrn.info("Process p = Runtime.getRuntime().exec(cmdArray, null, workDir);");
	    Thread t1 = new InputStreamTracer(p.getInputStream(), jrn);
	    jrn.info("Thread t1 = new InputStreamTracer(p.getInputStream(), jrn);");
	    Thread t2 = new InputStreamTracer(p.getErrorStream(), jrn);
	    jrn.info("Thread t2 = new InputStreamTracer(p.getInputStream(), jrn);");
	    t1.start();
	    jrn.info("t1.start();");
	    t2.start();
	    jrn.info("t2.start();");
	    /*t1.join();
	    jrn.info("t1.join()");
	    t2.join();
	    jrn.info("t2.join()");
		*/
	    
		return p.waitFor();
	}
}

class InputStreamTracer extends Thread
{
	InputStream m_istream;
	Logger m_jrn;
	
	public InputStreamTracer(InputStream istream, Logger jrn)
	{
		m_istream = istream;
		m_jrn = jrn;
	}
	
	public void run()
	{
		StringBuffer outBuff = new StringBuffer();
		byte[] vBuff = new byte[256];
		int nLen = -1;
		int nTotal = 0;
		
		try
		{
			while (-1 < (nLen = m_istream.read(vBuff, 0, vBuff.length)))
			{
			    nTotal += nLen;
			    outBuff.append(new String(vBuff, 0, nLen));
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		} 
		
		m_jrn.info(outBuff);
	}
}

